package com.jinlejia.erp.ui.home;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.FullyGridLayoutManager;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.FormAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityHousingWhyBinding;
import com.jinlejia.erp.utils.DataFilter;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.alibaba.fastjson.JSON.parseObject;


/**
 * 房屋推荐理由(Adapter)
 */

public class VisitIntroduceActivity extends AppCompatActivity {

    private String reason;  //居室结构

    private ArrayList<String> data1 = new ArrayList<>();
    private Map<String, Object> map = new HashMap<String, Object>();
    private FormAdapter adapter;
    private FormAdapter houseTypeAdapter;
    private ArrayList<Map<String, Object>> cData = new ArrayList<>();

    private ActivityHousingWhyBinding binding;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_housing_why);
        binding.backBtn.setOnClickListener(this::onClick);
        binding.save.setOnClickListener(this::onClick);
        EventBus.getDefault().registerSticky(this);
        initView();
    }

    @Subscriber(tag = "TAG_DATA")
    private void getList(ArrayList<Map<String, Object>> cData) {
        EventBus.getDefault().removeStickyEvent(cData.getClass(), "TAG_DATA");
        this.cData = cData;
    }

    /**
     * 初始化视图
     */
    private void initView() {
        getData();
        binding.yfRecycler.setLayoutManager(new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false));
        adapter = new FormAdapter(data1);
        binding.yfRecycler.setAdapter(adapter);

        binding.houseTypeRecycler.setLayoutManager(new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false));
        houseTypeAdapter = new FormAdapter(new ArrayList<String>());
        binding.houseTypeRecycler.setAdapter(houseTypeAdapter);

        binding.inputContent.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = 200 - s.length();
                binding.textCount.setText(number + "/200");
                selectionStart = binding.inputContent.getSelectionStart();
                selectionEnd = binding.inputContent.getSelectionEnd();
                if (temp.length() > 200) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    binding.inputContent.setText(s);
                    binding.inputContent.setSelection(tempSelection);//设置光标在最后
                }
            }
        });

        adapter.setOnSelectedListiner(list -> {
            map.put("tags", ListToString(list));
            System.out.println( map.entrySet() );
        });

        houseTypeAdapter.setOnSelectedListiner(list -> {
            map.put("houseType", ListToString(list));
            System.out.println( map.entrySet() );
        });
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.save:
                reason = binding.inputContent.getText().toString();
                map.put("recommendReason", reason);
                cData.get(getIntent().getIntExtra("position", 0)).putAll(map);
                EventBus.getDefault().post(cData, "TAG_SELECT_TAG");
                finish();
                break;
        }
    }

    /**
     * 获取数据
     */
    public void getData() {
        OkHttpUtils
                .get()
                .url(ApiConfig.APPOINTMENT_TAG_LIST)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(VisitIntroduceActivity.this, response, null)) {
                            JSONObject object = parseObject(response.get("data").toString());
                            ArrayList<String> houseTypesList = JSON.parseObject(object.get("houseTypesList").toString(), new TypeReference<ArrayList<String>>() {
                            });
                            ArrayList<String> tagList = JSON.parseObject(object.get("tagList").toString(), new TypeReference<ArrayList<String>>() {
                            });
                            adapter.setData(tagList);
                            if(  cData.get(getIntent().getIntExtra("position", 0)).containsKey("tags") && null!=cData.get(getIntent().getIntExtra("position", 0)).get("tags") ) {
                                String tag = cData.get(getIntent().getIntExtra("position", 0)).get("tags").toString();
                                ArrayList<String> tagListTmp = new ArrayList<>();
                                tagListTmp.addAll(Arrays.asList(tag.split(";")));
                                adapter.setHasCheck(tagListTmp);
                            }
                            houseTypeAdapter.setData(houseTypesList);
                            if(  cData.get(getIntent().getIntExtra("position", 0)).containsKey("houseType") && null!= cData.get(getIntent().getIntExtra("position", 0)).get("houseType")  ) {
                                String hType = cData.get(getIntent().getIntExtra("position", 0)).get("houseType").toString();
                                ArrayList<String> typeListTmp = new ArrayList<>();
                                typeListTmp.addAll(Arrays.asList(hType.split(";")));
                                houseTypeAdapter.setHasCheck( typeListTmp );
                            }

                            if(  cData.get(getIntent().getIntExtra("position", 0)).containsKey("recommendReason") && null != cData.get(getIntent().getIntExtra("position", 0)).get("recommendReason") ) {
                                binding.inputContent.setText (cData.get(getIntent().getIntExtra("position", 0)).get("recommendReason").toString() );
                            }
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public static String ListToString(List<String> stringList) {
        StringBuilder result = new StringBuilder();
        boolean flag = false;
        if (stringList == null) {
            return null;
        }
        for (String s : stringList) {
            if (flag) {
                result.append(";");
            } else {
                flag = true;
            }
            result.append(s);
        }
        return result.toString();
    }
}
